package com.its.interceptor;

import com.its.utils.AdminJwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AdminJwtAuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    private AdminJwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        String authHeader = request.getHeader("Authorization");
        System.out.println("authHeader:"+authHeader);
        if (authHeader != null) {
            String token = authHeader;
            String username = jwtUtils.getUsernameFromToken(token);
            System.out.println(username);
            if (username != null) {
                request.setAttribute("username", username);
                return true;
            }
        }
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        return false;
    }
}
